'''
Description: 
Author: Zilu
Date: 2021-11-10 15:56:39
Version: 
LastEditTime: 2021-11-10 16:21:33
LastEditors: Zilu
'''

import time, sys, queue
from multiprocessing.managers import BaseManager
from multiprocessing import Queue

# 创建类似的QueueManager
class QueueManager(BaseManager):
    pass

# 由于这个QueueManager只从网络上获取Queue，所以注册时只提供名字:
QueueManager.register('getTaskQueue')
QueueManager.register('getResultQueue')

# 连接到服务器
serverAddr = '127.0.0.1'
print('Connect to server %s...' % serverAddr)

# 端口和验证码保持与master的一致
m = QueueManager(address=(serverAddr, 5000),authkey=b'abc')

# 从网络连接
m.connect()

# 获取Queue对象
task = m.getTaskQueue()
result = m.getResultQueue()

# 从task读取任务，并把结果写入result
for i in range(10):
    try:
        n = task.get(timeout=1)
        print('run task %d * %d...' % (n, n))
        r = '%d * %d = %d' % (n, n, n*n)
        time.sleep(1)
        result.put(r)
    except Queue.Empty:
        print('task queue is empty')

#处理结束
print('worker exit.')

